package com.tanhua.dubbo.server.api;

import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.alibaba.dubbo.config.annotation.Service;


import java.util.List;

@Service(version = "1.0.0") //申明这是一个dubbo服务
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    //加载mongoTemplate
    private MongoTemplate mongoTemplate;

    /**
     * 查询得分最高的用户
     * @param userId
     * @return
     */
    @Override
    public RecommendUser queryWithMaxScore(Long userId) {
        //1.查询得分最高的用户，按照得分倒序排序
        //1.1封装了条件查询语句:(传入的用户id)Criteria进行查询,然后通过降序排序,查找出传入用户的缘分值匹配者
        Query query = Query.query(
                Criteria.where("toUserId").is(userId))
                .with(Sort.by(Sort.Order.desc("score"))).limit(1);

        //1.2 通过封装的mongoTemplate调用查询单个的方法,返回值的类型是RecommendUser推荐用户类型
        return this.mongoTemplate.findOne(query, RecommendUser.class);
    }

    /**
     * 查询用户信息
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<RecommendUser> queryPageInfo(Long userId, Integer pageNum, Integer pageSize) {

        //分页并且排序参数
        PageRequest pageRequest = PageRequest.of(pageNum -1 , pageSize, Sort.by(Sort.Order.desc("score")));

        //查询参数
        Query query = Query.query(Criteria.where("toUserId").is(userId)).with(pageRequest);

        List<RecommendUser> recommendUserList = this.mongoTemplate.find(query, RecommendUser.class);

        //暂时不提供数据总数
        return new PageInfo<>(0, pageNum, pageSize, recommendUserList);
    }

    /**
     * 查询推荐好友的缘分值
     * @param userId
     * @param toUserId
     * @return
     */
    @Override
    public double queryScore(Long userId, Long toUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("toUserId").is(toUserId));
        RecommendUser recommendUser = this.mongoTemplate.findOne(query,RecommendUser.class);

        if ( recommendUser == null){
            return 0;
        }

        return recommendUser.getScore();
    }


}
